package main.java.com.cliang.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 编码过滤器
 */
public class CharacterEncodingFilter implements Filter {
    private String encode="UTF-8";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String encoding=filterConfig.getInitParameter("encode");
        if(encoding!=null)
            encode=encoding;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        HttpServletRequest request= (HttpServletRequest) servletRequest;
//        HttpServletResponse response= (HttpServletResponse) servletResponse;
//
//        request.setCharacterEncoding(encode);
//        response.setCharacterEncoding(encode);
//        response.setContentType("text/html;charset="+encode);
//        filterChain.doFilter(request,response);

        servletRequest.setCharacterEncoding(encode);
        servletResponse.setCharacterEncoding(encode);
        servletResponse.setContentType("text/html;charset="+encode);
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        encode=null;
    }
}
